package com.lemon.smartsafety.ui.activity.bind;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.Field;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.common.AreaVo;
import com.lemon.smartsafety.entity.common.CommonVo;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.entity.event.common.AreaSelectEvent;
import com.lemon.smartsafety.entity.event.common.SelectItemEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.BindInfoServices;
import com.lemon.smartsafety.listener.AreaType;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.activity.common.AreaProvinceActivity;
import com.lemon.smartsafety.ui.activity.common.IndustryActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.DateUtils;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Cooliean on 16/4/9.
 */
public class CompanyPropInfoActivity extends SwipeBackActivity {

    @Bind(R.id.metComName)
    MaterialEditText metComName;
    @Bind(R.id.metCode)
    MaterialEditText metCode;
    @Bind(R.id.metLegalPerson)
    MaterialEditText metLegalPerson;
    @Bind(R.id.metLegalPhone)
    MaterialEditText metLegalPhone;
    @Bind(R.id.metRespPerson)
    MaterialEditText metRespPerson;
    @Bind(R.id.metRespPhone)
    MaterialEditText metRespPhone;
    @Bind(R.id.metArea)
    MaterialEditText metArea;
    @Bind(R.id.arrowArea)
    ImageView        arrowArea;
    @Bind(R.id.rowArea)
    TableRow         rowArea;
    @Bind(R.id.metIndustry)
    MaterialEditText metIndustry;
    @Bind(R.id.arrowIndustry)
    ImageView        arrowIndustry;
    @Bind(R.id.rowIndustry)
    TableRow         rowIndustry;
    @Bind(R.id.btn_submit)
    Button           btnSubmit;
    @Bind(R.id.tl_basic_info)
    TableLayout      tlBasicInfo;


    private LoggerHelper loggerHelper = new LoggerHelper(CompanyPropInfoActivity.class);


    /**
     * 不能修改
     */
    private boolean bCantEdit        = false;
    private String  mApplicationCode = null;

    private CompanyInfo mComInfoVo;
    private SelectDataI mIndustry;

    private SelectDataI mAreaProvince, mAreaCity, mAreaDistrict, mAreaStreet, mAreaVillage;


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mApplicationCode = getIntent().getStringExtra(BundleKey.APPLICATION_CODE);
            bCantEdit = getIntent().getBooleanExtra(BundleKey.CANT_EDIT, false);
            mComInfoVo = (CompanyInfo) getIntent().getSerializableExtra(BundleKey.COM_INFO);
        }
        mApplicationCode = StringUtils.nullValue(mApplicationCode);
    }


    @Override
    protected void initTitle() {
        setBarTitle("企业信息");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(CompanyPropInfoActivity.this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected int getContentViewId() {
        return R.layout.activity_bind_company_prop;
    }

    @Override
    protected void initViews() {
        super.initViews();

        metIndustry.setTag("");

        if (bCantEdit && null == mComInfoVo) {
            mHUDUtil.showErrorTip(getString(R.string.params_error), new HUDUtil.CallBack() {
                @Override
                public void onCall() {
                    callFinish();
                }
            });
        }

        /**
         * 这里选择过来的
         */
        if (bCantEdit && null != mComInfoVo) {
            initInfoView(mComInfoVo);
        } else {
            arrowArea.setVisibility(View.VISIBLE);
            arrowIndustry.setVisibility(View.VISIBLE);
        }
    }

    private void initInfoView(CompanyInfo infoVo) {
        //loggerHelper.json(govInfoVo);

        metComName.setText(StringUtils.nullValue(infoVo.getCompany_name()));
        metCode.setText(StringUtils.nullValue(infoVo.getCompany_code()));

        metLegalPerson.setText(StringUtils.nullValue(infoVo.getLegal_person()));
        if(StringUtils.nullValue(infoVo.getLegal_person_phone())!=""){
            // metLegalPhone.setText(StringUtils.nullValue(infoVo.getLegal_person_phone()));
            metLegalPhone.setText("************");
        }
        if(StringUtils.nullValue(infoVo.getPrincipal_name())!="") {
            metRespPerson.setText("***");
        }
        if(StringUtils.nullValue(infoVo.getPrincipal_phone())!="") {
            metRespPhone.setText("**********");
        }

       // metRespPerson.setText(StringUtils.nullValue(infoVo.getPrincipal_name()));
        //metRespPhone.setText(StringUtils.nullValue(infoVo.getPrincipal_phone()));
        metArea.setText(getAreaText(infoVo));

        metIndustry.setText(StringUtils.nullValue(infoVo.getIndustry_type_name()));
        metIndustry.setTag(StringUtils.nullValue(infoVo.getIndustry_type_id()));

        CommonVo industryVo = new CommonVo();
        industryVo.setId(StringUtils.nullValue(infoVo.getIndustry_type_id()));
        industryVo.setSelected(true);
        industryVo.setName(StringUtils.nullValue(infoVo.getIndustry_type_name()));
        mIndustry = industryVo;

        arrowArea.setVisibility(View.GONE);
        arrowIndustry.setVisibility(View.GONE);


        disableFormWithOutButton(tlBasicInfo);
    }

    private String getAreaText(CompanyInfo govInfoVo) {
        StringBuilder sb    = new StringBuilder();
        String        title = StringUtils.nullValue(govInfoVo.getPlace_name_province());
        if (title.length() != 0) {
            sb.append(title);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title);
            vo.setVoId(StringUtils.nullValue(govInfoVo.getPosition_province_id()));
            mAreaProvince = vo;
        }

        String title2 = StringUtils.nullValue(govInfoVo.getPlace_name_city());
        if (title2.length() != 0) {
            sb.append("-" + title2);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title2);
            vo.setVoId(StringUtils.nullValue(govInfoVo.getPosition_city_id()));
            mAreaCity = vo;
        } else {
            mAreaCity = null;
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }

        String title3 = StringUtils.nullValue(govInfoVo.getPlace_name_district());
        if (title3.length() != 0) {
            sb.append("-" + title3);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title3);
            vo.setVoId(StringUtils.nullValue(govInfoVo.getPosition_district_id()));
            mAreaDistrict = vo;
        } else {
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }
        String title4 = StringUtils.nullValue(govInfoVo.getPlace_name_streets());
        if (title4.length() != 0) {
            sb.append("-" + title4);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title4);
            vo.setVoId(StringUtils.nullValue(govInfoVo.getPosition_streets_id()));
            mAreaStreet = vo;
        } else {
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }

        String title5 = StringUtils.nullValue(govInfoVo.getPlace_name_village());
        if (title5.length() != 0) {
            sb.append("-" + title5);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title5);
            vo.setVoId(StringUtils.nullValue(govInfoVo.getPosition_village_id()));
            mAreaVillage = vo;
        } else {
            mAreaVillage = null;
        }
        return sb.toString();
    }


    @OnClick({R.id.btn_submit})
    public void submitAction(View view) {
        if (!validateForm()) {
            return;
        }
        getConfirmDialog("是否绑定？", new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    if (!bCantEdit) {
                        doSubmitAction();
                    } else {
                        bindInfoAction();
                    }
                }
            }
        }).show();

    }

    /**
     * 保存新的机构信息
     */
    private void doSubmitAction() {
        final LemonRequestParams params = new LemonRequestParams("company_info", "company_id", "");

        params.put("_txtIdValues", "");
        params.put("bind_id", "");
        params.put("application_code", mApplicationCode);
        params.put("txtCompanyName", metComName.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtCompanyCode", metCode.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtLegalPerson", metLegalPerson.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtLegalPersonPhone", metLegalPhone.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtPrincipalName", metRespPerson.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtPrincipalPhone", metRespPhone.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtRecordDate", DateUtils.getCurrentYMDHMSDate(), Field.TYPE_DATE);
        params.put("txtLastModifiedDate", DateUtils.getCurrentYMDHMSDate(), Field.TYPE_DATE);
        params.put("txtRecorderId", mSharedPreferencesHelper.getUserId(), Field.TYPE_STRING);
        params.put("selIndustryTypeId", mIndustry.getValue(), Field.TYPE_STRING);

        if (mAreaProvince != null) {
            params.put("selPositionProvinceId", mAreaProvince.getValue(), Field.TYPE_STRING);
        }
        if (mAreaCity != null) {
            params.put("selPositionCityId", mAreaCity.getValue(), Field.TYPE_STRING);
        }
        if (mAreaDistrict != null) {
            params.put("selPositionDistrictId", mAreaDistrict.getValue(), Field.TYPE_STRING);
        }
        if (mAreaStreet != null) {
            params.put("selPositionStreetsId", mAreaStreet.getValue(), Field.TYPE_STRING);
        }
        if (mAreaVillage != null) {
            params.put("selPositionVillageId", mAreaVillage.getValue(), Field.TYPE_STRING);
        }
        BindInfoServices.init().saveComInfoAction(params, false);
    }

    /**
     * 绑定现有的机构
     */
    private void bindInfoAction() {
        final LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");

        params.put("_txtIdValues", "");
        params.put("bind_id", "");
        params.put("txtApplicationCode", mApplicationCode, Field.TYPE_STRING);
        params.put("txtUserId", mSharedPreferencesHelper.getUserId(), Field.TYPE_STRING);
        params.put("txtBindDate", DateUtils.getCurrentYMDHMSDate(), Field.TYPE_DATETIME);
        params.put("txtStatus", "0", Field.TYPE_INT);
        params.put("txtBindType", "company", Field.TYPE_STRING);
        params.put("txtBindCode", metCode.getText().toString().trim(), Field.TYPE_STRING);

        BindInfoServices.init().saveApplicationInfo(params);
    }

    private boolean validateForm() {
        if (bCantEdit) {//若果是选择的机构直接就不检验表单了
            return true;
        }
        if (TextUtils.isEmpty(metComName.getText().toString().trim())) {
            metComName.setError("请填写企业名称");
            mHUDUtil.showErrorTip(metComName.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metCode.getText().toString().trim())) {
            metCode.setError("请填写机构代码");
            mHUDUtil.showErrorTip(metCode.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metLegalPerson.getText().toString().trim())) {
            metLegalPerson.setError("请填写法人名称");
            mHUDUtil.showErrorTip(metLegalPerson.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metLegalPhone.getText().toString().trim())) {
            metLegalPhone.setError("请填写法人电话");
            mHUDUtil.showErrorTip(metLegalPhone.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metRespPerson.getText().toString().trim())) {
            metRespPerson.setError("请填写企业负责人");
            mHUDUtil.showErrorTip(metRespPerson.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metRespPhone.getText().toString().trim())) {
            metRespPhone.setError("请填写企业负责人电话");
            mHUDUtil.showErrorTip(metRespPhone.getError().toString());
            return false;
        }


        if (TextUtils.isEmpty(metArea.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请选择属地");
            return false;
        }



        if (TextUtils.isEmpty(metIndustry.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请选择行业");
            return false;
        }
        return true;
    }


    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.TAG_BIND_SAVE_ACTION.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            AppManager.getAppManager().finishActivity(CompanyPropInfoActivity.class);
                            AppManager.getAppManager().finishActivity(BindCompanyListActivity.class);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    @OnClick({R.id.metArea, R.id.rowArea, R.id.rowIndustry, R.id.metIndustry})
    public void onClick(View view) {
        if (view.getId() == R.id.metArea || view.getId() == R.id.rowArea) {//地域选择
            Bundle bundle = new Bundle();
            bundle.putBoolean(BundleKey.IS_FOR_REGISTER, false);
            UIHelper.showActivity(CompanyPropInfoActivity.this, bundle, AreaProvinceActivity.class);
        } else if (view.getId() == R.id.rowIndustry || view.getId() == R.id.metIndustry) {//行业
            Bundle bundle = new Bundle();
            bundle.putBoolean(BundleKey.IS_MULTI_SELECT, false);
            if (null != mIndustry) {
                bundle.putSerializable(BundleKey.OLD_SELECT_VALUE, StringUtils.nullValue(mIndustry.getValue()));
            }
            UIHelper.showActivity(this, bundle, IndustryActivity.class);

        }
    }


    @Subscribe
    public void onEventMainThread(AreaSelectEvent event) {
        if (AreaType.PROVINCE == event.getType()) {
            mAreaProvince = event.getData();
        } else if (AreaType.CITY == event.getType()) {
            mAreaCity = event.getData();
        } else if (AreaType.DISTRICT == event.getType()) {
            mAreaDistrict = event.getData();
        } else if (AreaType.STREET == event.getType()) {
            mAreaStreet = event.getData();
        } else if (AreaType.VILLAGE == event.getType()) {
            mAreaVillage = event.getData();
        }
        loggerHelper.w(getAreaViewValue());
        metArea.setText(getAreaViewValue());
    }

    private String getAreaViewValue() {
        StringBuilder sb = new StringBuilder();
        if (mAreaProvince != null) {
            String title = StringUtils.nullValue(mAreaProvince.getTitle());
            sb.append(title);
        } else {
            return sb.toString();
        }
        if (mAreaCity != null) {
            String title = StringUtils.nullValue(mAreaCity.getTitle());
            sb.append("-" + title);
        } else {
            mAreaCity = null;
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }

        if (mAreaDistrict != null) {
            String title = StringUtils.nullValue(mAreaDistrict.getTitle());
            sb.append("-" + title);
        } else {
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }


        if (mAreaStreet != null) {
            String title = StringUtils.nullValue(mAreaStreet.getTitle());
            sb.append("-" + title);
        } else {
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }


        if (mAreaVillage != null) {
            String title = StringUtils.nullValue(mAreaVillage.getTitle());
            sb.append("-" + title);
        } else {
            mAreaVillage = null;
        }

        return sb.toString();
    }


    @Subscribe
    public void onEventMainThread(SelectItemEvent event) {
        if (event.getTag().equals(EventTag.TAG_INDUSTRY)) {
            mIndustry = event.getData();
            metIndustry.setText(mIndustry.getTitle());
            metIndustry.setTag(StringUtils.nullValue(mIndustry.getValue()));
        }
    }


}